<script setup lang="ts">
import { ref } from 'vue'
// 用uni-app的声明周期
import { onLoad } from '@dcloudio/uni-app'
// 局部组件导入
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
// 骨架屏
import PageSkeleton from './components/PageSkeleton.vue'
// api接口导入
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'

// 导入类型
import type { BannerItem, CategoryItem, HotItem, GuessItem } from '@/types/home'
import type { XtxGuessInstance } from '@/types/component'
import { useGuessList } from '@/composables'

let BannerList = ref<BannerItem[]>([])
let CategoryList = ref<CategoryItem[]>([])
let HotList = ref<HotItem[]>([])
/*
  @description: 获取首页的Banner数据
*/
const getHomeBannerData = async () => {
  let res = await getHomeBannerAPI()
  BannerList.value = res.result
}

/*
  @description: 获取首页的Category分类数据
*/
const getHomeCategoryData = async () => {
  let res = await getHomeCategoryAPI()
  CategoryList.value = res.result
}

/*
  @description: 获取首页的Hot热门推荐数据
*/
const getHomeHotData = async () => {
  let res = await getHomeHotAPI()
  HotList.value = res.result
}
// 控制骨架屏显示
let isLoading = ref(true)

onLoad(async () => {
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})

// // 猜你喜欢组件实例
// let guessRef = ref<XtxGuessInstance>()

// 滚动到底部的事件hooks
let { onScrolltolower, guessRef } = useGuessList()

// 控制下拉刷新动画
let isTriggered = ref(false)

// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  isLoading.value = true
  isTriggered.value = true
  // 重设"猜你喜欢"组件的数据
  guessRef.value?.resetData()
  // promise.all执行所有异步任务
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.getMore(),
  ])
  isTriggered.value = false
  isLoading.value = false
}
</script>

<template>
  <view class="viewport">
    <CustomNavbar></CustomNavbar>
    <PageSkeleton v-if="isLoading"></PageSkeleton>
    <template v-else>
      <!-- 1. 顶部导航部分 -->
      <scroll-view
        :refresher-triggered="isTriggered"
        :refresher-enabled="true"
        @refresherrefresh="onRefresherrefresh"
        class="scroll-view"
        scroll-y
        @scrolltolower="onScrolltolower"
      >
        <!-- 2.Banner轮播图 -->
        <XtxSwiper :list="BannerList"></XtxSwiper>
        <!-- 3.分类仪表盘 -->
        <CategoryPanel :list="CategoryList"></CategoryPanel>
        <!-- 4.热门推荐 -->
        <HotPanel :list="HotList"></HotPanel>
        <!-- 5.猜你喜欢 -->
        <XtxGuess ref="guessRef"></XtxGuess>
      </scroll-view>
    </template>
  </view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  overflow: hidden;
}
.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.scroll-view {
  flex: 1;
  overflow: hidden;
}
</style>
